#!/sbin/openrc-run

: ${name:="$RC_SVCNAME"}
: ${command:="java"}
: ${command_user:=${user:-"nobody"}}
: ${retry:="SIGTERM/20"}
: ${start_wait=200}  # milliseconds
: ${jetty_runner:="/usr/share/java/jetty-runner.jar"}

command_background="true"
pidfile="/run/$RC_SVCNAME.pid"

start_stop_daemon_args="${start_wait:+"--wait $start_wait"} ${start_stop_daemon_args-}"
# See https://github.com/OpenRC/openrc/pull/558
supervise_daemon_args="$supervise_daemon_args"

required_files="$webapp_path"

depend() {
	need net
}

start_pre() {
	if [ "$RC_SVCNAME" = "jetty-runner" ]; then
		ewarn "You are not supposed to run this runscript directly. Instead, you should"
		ewarn "create a symlink for the application you want to run as well as a copy of"
		ewarn "the configuration file and modify it appropriately, like so:"
		ewarn ""
		ewarn "    ln -s jetty-runner /etc/init.d/myapp"
		ewarn "    cp /etc/conf.d/jetty-runner /etc/conf.d/myapp"
		ewarn ""
	fi

	if [ "${server_out_log-}" ]; then
		if [ "${server_out_log%/*}" = '/var/log' ]; then
			eerror "server_out_log must not be directly in /var/log, choose a subdirectory"
			return 1
		fi
		checkpath -d -o "$command_user" "${server_out_log%/*}"
	fi

	if [ "${server_access_log-}" ]; then
		if [ "${server_access_log%/*}" = '/var/log' ]; then
			eerror "server_access_log must not be directly in /var/log, choose a subdirectory"
			return 1
		fi
		checkpath -d -o "$command_user" "${server_access_log%/*}"
	fi

	if [ "${server_port-}" ] && nc -z 127.0.0.1 "$server_port"; then
		eerror "Port $server_port is already in use!"; return 1
	fi

	java_opts="
		-server
		${java_heap_size:+ -Xms${java_heap_size}M -Xmx${java_heap_size}M}
		${java_new_ratio:+ -XX:NewRatio=${java_new_ratio}}
		-Dfile.encoding=utf-8
		$java_opts"

	local item; for item in $java_properties; do
		java_opts="$java_opts -D${item}"
	done

	jetty_opts="
		$(optif --port "$server_port")
		$(optif --host "$server_bind_address")
		$(optif --out  "$server_out_log")
		$(optif --log  "$server_access_log")"

	local path; for path in ${server_extra_jars//:/ }; do
		if [ -f "$path" ]; then
			jetty_opts="$jetty_opts --jar $path"
		elif [ -d "$path" ]; then
			jetty_opts="$jetty_opts --lib $path"
		else
			ewarn "JAR file or directory $path does not exist!"
		fi
	done

	jetty_opts="$jetty_opts $(optif --path "$context_root") $webapp_path"

	command_args="$java_opts -cp $jetty_runner org.eclipse.jetty.runner.Runner $jetty_opts"
}

optif() {
	test -n "$2" && echo "$1 $2"
}
